浏览量 4282
2019/05/10 18:23
项目地址
安装
pip install pysnooper
使用举例
跟踪整个函数
用例: 编写一个函数,它通过返回一个位列表来将一个数转换成二进制。通过加@pysnooper.snoop() 装饰器,来举例pysnooper的使用方法.
#!/usr/bin/env python
# coding=utf-8
# author: wz
# mail: 277215243@qq.com
# datetime:2019/5/10 5:31 PM
# web: https://www.bthlt.com
import pysnooper
@pysnooper.snoop()
def number_to_bits(number):
if number:
bits = []
while number:
number, remainder = divmod(number, 2)
bits.insert(0, remainder)
return bits
else:
return [0]
number_to_bits(6)
输出:
Starting var:.. number = 6
17:31:48.186679 call 9 def number_to_bits(number):
17:31:48.186884 line 10 if number:
17:31:48.186913 line 11 bits = []
New var:....... bits = []
17:31:48.186950 line 12 while number:
17:31:48.186973 line 13 number, remainder = divmod(number, 2)
New var:....... remainder = 0
Modified var:.. number = 3
17:31:48.187016 line 14 bits.insert(0, remainder)
Modified var:.. bits = [0]
17:31:48.187051 line 12 while number:
17:31:48.187076 line 13 number, remainder = divmod(number, 2)
Modified var:.. number = 1
Modified var:.. remainder = 1
17:31:48.187118 line 14 bits.insert(0, remainder)
Modified var:.. bits = [1, 0]
17:31:48.187151 line 12 while number:
17:31:48.187175 line 13 number, remainder = divmod(number, 2)
Modified var:.. number = 0
17:31:48.187208 line 14 bits.insert(0, remainder)
Modified var:.. bits = [1, 1, 0]
17:31:48.187242 line 12 while number:
17:31:48.187265 line 15 return bits
17:31:48.187290 return 15 return bits
Return value:.. [1, 1, 0]
跟踪部分函数
用例:如果不想跟踪整个函数,可以将相关的部分打包成块:
#!/usr/bin/env python
# coding=utf-8
# author: wz
# mail: 277215243@qq.com
# datetime:2019/5/10 5:31 PM
# web: https://www.bthlt.com
import pysnooper
import random
def foo():
lst = []
for i in range(10):
lst.append(random.randrange(1, 1000))
with pysnooper.snoop():
lower = min(lst)
upper = max(lst)
mid = (lower + upper) / 2
print(lower, mid, upper)
foo()
输出:
New var:....... i = 9
117 535.5 954
New var:....... lst = [622, 795, 946, 518, 954, 848, 117, 480, 292, 885]
17:46:48.497081 line 16 lower = min(lst)
New var:....... lower = 117
17:46:48.497306 line 17 upper = max(lst)
New var:....... upper = 954
17:46:48.497350 line 18 mid = (lower + upper) / 2
New var:....... mid = 535.5
17:46:48.497684 line 19 print(lower, mid, upper)
其他特性
如果不方便访问stderr,则可以重定向到文件:
@pysnooper.snoop('/my/log/file.log')
查看非局部变量的值:
@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))
显示函数调用的snoop行:
@pysnooper.snoop(depth=2)
窥探指定前缀的行:
上一篇 搜索 下一篇@pysnooper.snoop(prefix ='ZZZ')